// pages/order/quasi.js
import {
  getQuasiOrderInfo,
  updateOrderAddr,
  updateOrderCoupon,
  addOrder,
  getPayment,
  getUserAddrs,
  getStoreDetail
} from '../../utils/apis'

import { alert, requestPayment, getCurrentPage } from '../../utils/util'
const app = getApp()
Page({
  data: {
    content: '', //备注
    orderInfo: '',
    typeList: [
      { name: '外卖配送', id: '1', isShow: true },
      { name: '到店自取', id: '2', isShow: true },
      { name: '堂食预定', id: '3', isShow: true }
    ],
    peisongTime: '',
    currentTypeId: '1',
    peisongTime: '',
    info: {
      receiver_addr_id: '', //地址id
      receiver_addr: '', //地址
      receiver: '', //姓名,
      receiver_phone: '', //手机号,

      seller_name: '', //卖家名称
      goods: [],
      packing_fee: '',
      delivery_fee: '',
      pay_price: '',
      cut_money_total: ''
    },
    totalPrice: '',
    eatTime: '',
    dispatchTime: '', //配送时间
    dinnerware: '',
    page: 0,
    size: 10
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    // this.loadData()
  },
  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
    this.loadData()
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
  loadData() {
    var { loading, page, size, currentTypeId } = this.data
    var that = this
    if (loading) {
      return
    }
    //读取购物车信息
    console.log(app.globalData.order)
    var shopCarInfo = app.globalData.order

    that.setData({
      orderInfo: shopCarInfo,
      info: Object.assign(that.data.info, {
        packing_fee: shopCarInfo.packagePrice,
        delivery_fee: shopCarInfo.expressPrice,
        pay_price: shopCarInfo.price,
        productPrice: shopCarInfo.productPrice,
        goods: shopCarInfo.productList,
        reducePrice: shopCarInfo.price - shopCarInfo.payPrice
      }),
      //totalPrice: shopCarInfo.packagePrice + shopCarInfo.expressPrice + shopCarInfo.productPrice,
      totalPrice:
        shopCarInfo.productPrice +
        (currentTypeId != '3' ? shopCarInfo.packagePrice : 0) +
        (currentTypeId == '1' ? shopCarInfo.expressPrice : 0),
      eatTime: that.getDefaultTime().formatDate
    })
    //获取地址列表展示默认地址
    wx.showNavigationBarLoading()

    getUserAddrs({ page, size })
      .then(data => {
        console.log(selectAddr)
        var selectAddr = ''
        ;[].concat(data).map(function(item) {
          if (item.type > 0) {
            selectAddr = item
          }
        })
        console.log(selectAddr)
        that.setData({
          info: Object.assign(that.data.info, {
            receiver_addr_id: selectAddr.id,
            receiver_addr: selectAddr.areaName + ' ' + selectAddr.addressDetail,
            receiver: selectAddr.nickname,
            receiver_phone: selectAddr.phone
          }),
          loading: false
        })
        wx.hideNavigationBarLoading()
      })
      .catch(err => {
        that.setData({
          loading: false
        })
        wx.hideNavigationBarLoading()
      })

    //获取店铺详情
    getStoreDetail({ id: shopCarInfo.storeId })
      .then(data => {
        console.log(data)
        that.setData({
          typeList: [
            { name: '外卖配送', id: '1', isShow: data.takeOut > 0 },
            { name: '到店自取', id: '2', isShow: data.canPick > 0 },
            { name: '堂食预定', id: '3', isShow: data.eatIn > 0 }
          ],

          dispatchTime: data.dispatchTime,
          peisongTime: data.dispatchTime
            ? that.getNowTime(data.dispatchTime).formatDate
            : '及时配送',
          // ms: that.getNowTime(data.dispatchTime).ms,
          info: Object.assign(that.data.info, {
            seller_name: data.name
          })
        })
        this.setData({
          currentTypeId: [].concat(this.data.typeList).filter(item => {
            return item.isShow
          })[0].id
        })
      })
      .catch(err => {
        that.setData({
          loading: false
        })
        wx.hideNavigationBarLoading()
      })
  },

  callbackContent(content) {
    //备注
    this.setData({
      content
    })
  },
  setPsType(e) {
    //设置配送方式
    e.currentTarget.id
    this.setData({
      currentTypeId: e.currentTarget.id,
      totalPrice:
        app.globalData.order.productPrice +
        (e.currentTarget.id != '3' ? app.globalData.order.packagePrice : 0) +
        (e.currentTarget.id == '1' ? app.globalData.order.expressPrice : 0)
    })
  },
  onAddOrder(e) {
    //提交订单
    var that = this
    var { id } = this
    var {
      loading,
      content,
      info,
      orderInfo,
      currentTypeId,
      dinnerware,
      eatTime,
      dispatchTime
    } = this.data
    if (loading) {
      return
    }
    if (currentTypeId == '1' && !info.receiver_addr_id) {
      return alert('请选择收货地址')
    }
    this.setData({
      loading: true
    })
    app.getLoginInfo(loginInfo => {
      if (!loginInfo) {
        return alert('用户未登录')
      } else {
        addOrder({
          orderinfo: {
            productList: info.goods,
            source: '1',
            storeId: orderInfo.storeId,
            bossId: orderInfo.bossId,
            expressType: 1,
            addressId: info.receiver_addr_id,
            phone: info.receiver_phone,
            // arrivedTime: currentTypeId == 1 ? ms : that.getDefaultTime().ms, //自取的时候按当前时间20分钟处理
            arrivedTime:
              currentTypeId == 1
                ? that.getNowTime(dispatchTime).ms
                : that.getSetTime1(eatTime + ':00'),
            payType: 0,
            remark: content,
            price:
              orderInfo.price -
              (currentTypeId == 1 ? 0 : orderInfo.expressPrice) -
              (currentTypeId == 3 ? orderInfo.packagePrice : 0),
            payPrice:
              orderInfo.payPrice -
              (currentTypeId == 1 ? 0 : orderInfo.expressPrice) -
              (currentTypeId == 3 ? orderInfo.packagePrice : 0),
            productPrice: orderInfo.productPrice,
            packagePrice: currentTypeId == 3 ? 0 : orderInfo.packagePrice,
            expressPrice: currentTypeId == 1 ? orderInfo.expressPrice : 0,
            dinnerware: dinnerware,
            type: currentTypeId
          }
        })
          .then(data => {
            that.setData({
              loading: false
            })

            console.log(data)
            if (!data.inventoryList) {
              // 发起支付
              requestPayment({
                data,
                complete() {
                  console.log(111)
                  that.setData({
                    loading: false
                  })
                  wx.switchTab({
                    url: '/pages/order/list',
                    success(res) {
                      var { callback } = getCurrentPage()
                      callback && callback()
                    }
                  })
                }
              })
            } else if (data.inventoryList.length != 0) {
              // 库存不足
              let goods_str = ''

              data.inventoryList.forEach(item => {
                const good_name = info.goods.filter(
                  v => v.productId == item.productId
                )[0].productName
                if (good_name) goods_str = goods_str + good_name + ','
              })

              return alert(`${goods_str}库存不足`)
            }
          })
          .catch(_res => {
            if ((_res = 'requestPayment:fail cancel')) {
              //手动取消
            } else {
              //接口500
            }
            that.setData({
              loading: false
            })
          })
      }
    })

    // addOrder({ //新订单
    //     orderinfo: {
    //         productList: info.goods,
    //         source: '1',
    //         storeId: orderInfo.storeId,
    //         bossId: orderInfo.bossId,
    //         expressType: 1,
    //         addressId: info.receiver_addr_id,
    //         phone: info.receiver_phone,
    //         arrivedTime: currentTypeId == 1 ? ms : that.getSetTime1(eatTime),
    //         payType: 0,
    //         remark: content,
    //         price: orderInfo.price - (currentTypeId == 1 ? 0 : orderInfo.expressPrice),
    //         payPrice: orderInfo.payPrice - (currentTypeId == 1 ? 0 : orderInfo.expressPrice),
    //         productPrice: orderInfo.productPrice,
    //         packagePrice: orderInfo.packagePrice,
    //         expressPrice: orderInfo.expressPrice,
    //         dinnerware: dinnerware,
    //         type: currentTypeId
    //     },
    //     success(data) {
    //         console.log(data);
    //         that.setData({
    //             loading: false
    //         })
    //         if (data.code != 100000) return;
    //         requestPayment({
    //             data,
    //             complete() {
    //                 that.setData({
    //                     loading: false
    //                 })
    //                 wx.switchTab({
    //                     url: '/pages/order/list',
    //                     success(res) {
    //                         var { callback } = getCurrentPage()
    //                         callback && callback()
    //                     }
    //                 })
    //             }
    //         })

    //     },
    //     error(_res) {
    //         if ((_res = 'requestPayment:fail cancel')) { //手动取消

    //         } else { //接口500

    //         }
    //         that.setData({
    //             loading: false
    //         })
    //     }
    // })
  },
  getNowTime(fen) {
    if (!fen) return 0
    var now = new Date(new Date().getTime() + fen * 60 * 1000)
    var hour = now.getHours()
    var minute = now.getMinutes()
    var second = now.getSeconds()
    var formatDate =
      (hour < 10 ? '0' + hour : hour) +
      ':' +
      (minute < 10 ? '0' + minute : minute) +
      ':' +
      (second < 10 ? '0' + second : second)
    console.log(formatDate)
    return {
      formatDate: formatDate,
      ms: new Date().getTime() + fen * 60 * 1000
    }
  },

  getSetTime1(time) {
    //传时分秒
    if (!time) return 0
    var now = new Date()
    var year = now.getFullYear()
    var month = now.getMonth() + 1
    var date = now.getDate()
    var date11 = year + '-' + month + '-' + date
    var now1 = new Date(year + '/' + month + '/' + date + ' ' + time)
    return now1.getTime()
  },
  getDefaultTime() {
    var now = new Date(new Date().getTime() + 20 * 60 * 1000)
    var hour = now.getHours()
    var minute = now.getMinutes()
    var second = now.getSeconds()

    var formatDate =
      (hour < 10 ? '0' + hour : hour) +
      ':' +
      (minute < 10 ? '0' + minute : minute)
    return { formatDate: formatDate, ms: new Date().getTime() + 20 * 60 * 1000 }
  },
  // onInputTime(e) {
  //     this.setData({
  //         eatTime: e.detail.value
  //     })
  // },
  onDinnerware(e) {
    this.setData({
      dinnerware: e.detail.value
    })
  },
  bindTimeChange: function(e) {
    this.setData({
      eatTime: e.detail.value
    })
    this.setData({
      peisongTime: this.getNowTime(this.data.dispatchTime).formatDate
    })
  }

  // callbackAddress(addr_id) {
  //     var that = this
  //     var { id } = this
  //     var { loading } = this.data
  //     if (loading) {
  //         return
  //     }
  //     this.setData({
  //         loading: true
  //     })
  //     wx.showNavigationBarLoading()
  //     updateOrderAddr({
  //         quasi_order_id: id,
  //         addr_id,
  //         success(data) {
  //             data['cut_money_total'] = +data.cut_money + +data.coupon_money
  //             that.setData({
  //                 info: data,
  //                 loading: false
  //             })
  //             wx.hideNavigationBarLoading()
  //         },
  //         error() {
  //             that.setData({
  //                 loading: false
  //             })
  //             wx.hideNavigationBarLoading()
  //         }
  //     })
  // },
  // callbackCoupon(user_coupon_id) {
  //     var that = this
  //     var { id } = this
  //     var { loading } = this.data
  //     if (loading) {
  //         return
  //     }
  //     this.setData({
  //         loading: true
  //     })
  //     wx.showNavigationBarLoading()
  //     updateOrderCoupon({
  //         quasi_order_id: id,
  //         user_coupon_id,
  //         success(data) {
  //             data['cut_money_total'] = +data.cut_money + +data.coupon_money
  //             that.setData({
  //                 info: data,
  //                 loading: false
  //             })
  //             wx.hideNavigationBarLoading()
  //         },
  //         error() {
  //             that.setData({
  //                 loading: false
  //             })
  //             wx.hideNavigationBarLoading()
  //         }
  //     })
  // },
})
